package com.onetime.mall.trading.utils;

import com.onetime.mall.trading.service.OrderService;

import java.util.concurrent.DelayQueue;

public class OrderTaskHandler {

    public static OrderService orderService = null;
    /**
     * 初始化延迟队列
     */
    private static DelayQueue<OrderTask> delayQueue = new DelayQueue<>();


    /**
     * 消费者
     */
    public static void run() {
        new Thread(() -> {
            System.out.println("成功创建线程！");
            while (true) {
                if (orderService != null && delayQueue.size() > 0) {
                    /*poll()返回DelayQueue的头部，并将其从此DelayQueue中删除*/
                    OrderTask poll = delayQueue.poll();
                    if (poll != null) {
                        if (orderService.updateOrder(poll.getOrderEntity())) {
                            System.out.println("成功取消订单：" + poll.getOrderEntity());
                        } else {
                            System.out.println("取消任务：" + poll.getOrderEntity());
                        }

                    }
                }
            }
        }).start();

    }

    /**
     * 生产者
     *
     * @param o
     */
    public static void addOrder(OrderTask o) {
        System.out.println("添加任务：" + o);
        delayQueue.put(o);
    }
}
